package com.yupi.yuoj.controller;

import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.membership.MembershipPurchaseRequest;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.MembershipVO;
import com.yupi.yuoj.service.MembershipService;
import com.yupi.yuoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 会员接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/user/membership")
@Slf4j
public class MembershipController {

    @Resource
    private MembershipService membershipService;

    @Resource
    private UserService userService;

    /**
     * 获取用户会员信息
     *
     * @param request
     * @return
     */
    @GetMapping("/info")
    public BaseResponse<MembershipVO> getMembershipInfo(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        MembershipVO membershipVO = membershipService.getUserMembership(loginUser);
        return ResultUtils.success(membershipVO);
    }

    /**
     * 购买会员
     *
     * @param purchaseRequest
     * @param request
     * @return
     */
    @PostMapping("/purchase")
    public BaseResponse<Boolean> purchaseMembership(@RequestBody MembershipPurchaseRequest purchaseRequest,
                                                   HttpServletRequest request) {
        ThrowUtils.throwIf(purchaseRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(purchaseRequest.getPlanId() == null, ErrorCode.PARAMS_ERROR, "套餐ID不能为空");
        ThrowUtils.throwIf(purchaseRequest.getDuration() == null || purchaseRequest.getDuration() <= 0, 
                ErrorCode.PARAMS_ERROR, "套餐时长不能为空");
        ThrowUtils.throwIf(purchaseRequest.getPrice() == null || purchaseRequest.getPrice().doubleValue() <= 0, 
                ErrorCode.PARAMS_ERROR, "套餐价格不能为空");

        User loginUser = userService.getLoginUser(request);
        boolean result = membershipService.purchaseMembership(purchaseRequest, loginUser);
        
        if (result) {
            log.info("用户 {} 购买会员成功，套餐：{}", loginUser.getId(), purchaseRequest.getPlanName());
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "购买失败，请重试");
        }
    }
}